package com.example.myapplication1;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

public class RateActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "Rate";
    public float dollarRate = 0.1f;
    public float euroRate = 0.01f;
    public float wonRate = 10f;
    TextView show;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    // 假设 msg.obj 是 Bundle 类型
                    Bundle bdl = (Bundle) msg.obj;
                    if (bdl != null) {
                        dollarRate = bdl.getFloat("web_dollar", dollarRate);
                        euroRate = bdl.getFloat("web_euro", euroRate);
                        wonRate = bdl.getFloat("web_won", wonRate);
                        Log.i(TAG, "handleMessage:dollarRate=" + dollarRate);
                        Log.i(TAG, "handleMessage:euroRate=" + euroRate);
                        Log.i(TAG, "handleMessage:wonRate=" + wonRate);
                    }
                }
                super.handleMessage(msg);
            }
        };
        show = findViewById(R.id.rmb_show);
        Log.i(TAG, "onCreate: start thread");
        Thread t = new Thread(this);
        t.start();// this.run()

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "run: Thread 222222222222");
            }
        });
        t2.start();

        Thread t3 = new Thread(()->{
            Log.i(TAG, "onCreate: thread 333333333333333");
        });
        t3.start();

        new Thread(()->{
            Log.i(TAG, "onCreate: thread 444444444444444");
        }).start();
    }

    public void click(View btn) {
        EditText input = findViewById(R.id.rmb);
        String inpStr = input.getText().toString();
        try {
            float rmb = Float.parseFloat(inpStr);
            float result = 0;
            if (btn.getId() == R.id.btn_dollar) {
                result = rmb * dollarRate;
            } else if (btn.getId() == R.id.btn_euro) {
                result = rmb * euroRate;
            } else if (btn.getId() == R.id.btn_won) {
                result = rmb * wonRate;
            }
            show.setText(String.valueOf(result));
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入正确数据", Toast.LENGTH_LONG).show();
        }
    }

    public void clickOpen(View btn) {
        Intent config = new Intent(this, ConfigActivity.class);
        config.putExtra("dollar_rate_key", dollarRate);
        config.putExtra("euro_rate_key", euroRate);
        config.putExtra("won_rate_key", wonRate);
        Log.i(TAG, "clickOpen:dollarRate" + dollarRate);
        Log.i(TAG, "clickOpen:euroRate" + euroRate);
        Log.i(TAG, "clickOpen:wonRate" + wonRate);
        startActivityForResult(config, 3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 3 && resultCode == 6) {
            Bundle bdl = data.getExtras();
            dollarRate = bdl.getFloat("key_dollar2", dollarRate);
            euroRate = bdl.getFloat("key_euro2", euroRate);
            wonRate = bdl.getFloat("key_won2", wonRate);
            Log.i(TAG, "OnActivityResult:dollarRate=" + dollarRate);
            Log.i(TAG, "OnActivityResult:euroRate=" + euroRate);
            Log.i(TAG, "OnActivityResult:wonRate=" + wonRate);
        }
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: Super method called.");
    }

    @Override
    public void run() {
        Log.i(TAG, "run;子线程run().....");
        URL url = null;
        Bundle retbd1 = new Bundle();
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Log.i(TAG, "run:title=" + doc.title());
            Elements tables = doc.getElementsByTag("table");
            Element table = tables.get(1);
            Log.i(TAG, "run:table2=" + table);
            Elements trs = table.getElementsByTag("tr");
            trs.remove(0);
            for (Element tr : trs) {
                Elements tds = tr.children();
                Element td1 = tds.first();
                Element td2 = tds.get(5);
                String str1 = td1.text();
                String str2 = td2.text();
                Log.i(TAG, "run:" + str1 + "==>" + str2);
                float r = 100 / Float.parseFloat(str2);
                if ("美元".equals(str1)) {
                    retbd1.putFloat("web_dollar", r);
                } else if ("欧元".equals(str1)) {
                    retbd1.putFloat("web_euro", r);
                } else if ("韩国元".equals(str1)) {
                    retbd1.putFloat("web_won", r);
                }
            }
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        }
        Message msg = handler.obtainMessage(5, retbd1);
        handler.sendMessage(msg);
    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "utf-8");
        while (true) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}